import { login, logout, getInfo, visitorLogin } from '@/api/user'
import { newlogin, newgetInfo, loginInfo } from '@/api/newuser'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter, constantRoutes } from '@/router'
import { MessageBox, Message } from 'element-ui'
import { userRouter } from "@/utils/userRouter"
import { newuserRouter } from "@/utils/newuserRouter"
import { newuserRouterChildren } from "@/utils/newuserRouterChildren"
import { adminRouter } from "@/utils/adminRouter"


const state = {
  token: getToken(),
  name: '',
  avatar: '',
  type: '',
  is_admin: '',
  is_admin_view: '',
  introduction: '',
  newtype: null,
  rid: '',
  roles: [],
  seach: '',
  menuList: [],
  allRouter: constantRoutes
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NEWTYPE: (state, newtype) => {
    state.newtype = newtype
  },
  SET_NEWTOKEN: (state, token) => {
    state.newtoken = token
  },

  SET_IS_ADMIN: (state, is_admin) => {
    state.is_admin = is_admin
  },
  SET_TYPE: (state, type) => {
    state.type = type
  },
  SET_ADMIN: (state, is_admin_view) => {
    state.is_admin_view = is_admin_view
  },
  SET_RID: (state, rid) => {
    state.rid = rid
  },
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_COMID: (state, com_id) => {
    state.com_id = com_id
  },
  SET_ADMINNAME: (state, admin_name) => {
    state.admin_name = admin_name
  },
  SET_PID: (state, pid) => {
    state.pid = pid
  },
  SET_STREETID: (state, street_id) => {
    state.street_id = street_id
  },
  SET_STREETNAME: (state, street_name) => {
    state.street_name = street_name
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ROUTER: (state, route) => {
    // console.log(route,'ROUTER')
    state.menuList = route;
    // state.allRouter = constantRoutes.concat(route)
    // console.log(state.menuList)
    // console.log(state.allRouter)
  },
}
const actions = {
  // user login
  login({ commit }, userInfo) {
    const { mobile, password, checked ,type } = userInfo;
    return new Promise((resolve, reject) => {
      login({ mobile: mobile.trim(), password: password , type: type }).then(response => {
        if (checked) {
          localStorage.setItem("mobile", mobile)
          localStorage.setItem("password", password)
        } else {
          localStorage.setItem("mobile", '')
          localStorage.setItem("password", '')
        }
        loginInfo({ account: mobile.trim(), password: password }).then(response => {
          sessionStorage.setItem("tokenIfon", response.token)
        })

        commit('SET_TOKEN', response.token)
        // console.log('type设置',type);
        if(type){
          commit('SET_NEWTYPE', type)
          sessionStorage.setItem("newtype", type)
        }else {
          commit('SET_NEWTYPE', 1)
          sessionStorage.setItem("newtype", 1)
        }
        
        setToken(response.token)
        sessionStorage.setItem("token", response.token)
        resolve()
      }).catch(error => {
        reject(error)
        Message.error({
          message: error,
          type: 'error',
        })
      })
    })
  },

  

  visitor({ commit }, userInfo) {
    const { mobile, code } = userInfo;
    // console.log(userInfo,'userInfo');
    return new Promise((resolve, reject) => {
      visitorLogin({ mobile: mobile.trim(), code: code }).then(response => {
        commit('SET_TOKEN', response.token)
        
        setToken(response.token)
        sessionStorage.setItem("token", response.token)
        resolve()
      }).catch(error => {
        reject(error)
        Message.error({
          message: error,
          type: 'error',
        })
      })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo({ tokens: state.token,type: Number(sessionStorage.getItem("newtype"))}).then(response => {
        if (!response) {
          reject('验证失败，请重新登录。')
        }
        const { is_admin, name,admin_name, avatar, introduction, type, is_admin_view, rid, id, com_id,pid,street_id,street_name } = response
        localStorage.setItem("avatar", avatar)
        // console.log(is_admin_view,1234)
        sessionStorage.getItem("user", is_admin)
        const roles = is_admin
        commit('SET_ROLES', roles)
        commit('SET_IS_ADMIN', is_admin)
        commit('SET_TYPE', type)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        commit('SET_ADMIN', is_admin_view)
        commit('SET_RID', rid)
        commit('SET_ID', id)
        commit('SET_COMID', com_id)
        commit('SET_ADMINNAME', admin_name)
        commit('SET_PID', pid)
        commit('SET_STREETID', street_id)
        commit('SET_STREETNAME', street_name)
        // roles must be a non-empty array
        // if (roles == '') {
        //   // roles 改 is_admin
        //   reject('getInfo: roles must be a non-null array!')
        // }

        resolve(response)

      }).catch(error => {
        reject(error)
        Message.error({
          message: error,
          type: 'error',
        })
      })
    })
  },


  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()
        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
        Message.error({
          message: error,
          type: 'error',
        })
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_NEWTOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resetRouter()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    // console.log(role,'role');
    return new Promise(async resolve => {
      // const token = role + '-token'

      // commit('SET_TOKEN', token)
      // setToken(token)

      const { is_admin, is_news, com_id } = await dispatch('getInfo')
      // resetRouter()
      // generate accessible routes map based on roles
      // const accessRoutes = await dispatch('permission/generateRoutes', is_admin, { root: true })
      if (is_news == 1) {
        if (com_id == 0) {
          const accessRoutes = newuserRouter;
          commit("SET_ROUTER", accessRoutes)
          router.addRoutes(accessRoutes)
          router.options.routes = accessRoutes
        } else {
          const accessRoutes = newuserRouterChildren;
          commit("SET_ROUTER", accessRoutes)
          router.addRoutes(accessRoutes)
          router.options.routes = accessRoutes
        }
      } else {
        if (is_admin == '0' || role.role == "0") {
          const accessRoutes = userRouter;
          commit("SET_ROUTER", accessRoutes)
          router.addRoutes(accessRoutes)
          router.options.routes = accessRoutes
        } else if (is_admin == '1' || role.role == "1") {
          const accessRoutes = adminRouter;
          commit("SET_ROUTER", accessRoutes)
          router.addRoutes(accessRoutes)
          router.options.routes = accessRoutes
        }
      }
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
